import { config, fs, DOWNLOAD_PATH, path } from "@/global";
import md5 from "js-md5";
import { Message } from "element-ui";

const getFileMD5 = function(filePath) {
  const file = fs.readFileSync(filePath);
  return md5(file);
};

const getChunkMD5 = async function(chunkBlob) {
  return new Promise((resolve, reject) => {
    const read = new FileReader();
    read.readAsArrayBuffer(chunkBlob);
    read.onload = r => resolve(md5(r.target.result));
    read.onerror = err => reject(err);
  });
};

const getChunkNum = function(filePath) {
  let stat = fs.statSync(filePath);
  return Math.ceil(stat.size / config.chunkSize);
};

const getChunk = async function(filePath, index) {
  return new Promise(function(resolve, reject) {
    let buff = [];
    let stat = fs.statSync(filePath);
    let end = Math.min(stat.size, index * config.chunkSize);
    let readStream = fs.createReadStream(filePath, {
      start: (index - 1) * config.chunkSize,
      end: end - 1
    });
    readStream.on("data", data => {
      buff.push(data);
    });
    readStream.on("end", () => {
      if (!buff) {
        reject("failed");
      }
      resolve(new Blob(buff));
    });
  });
};

const deleteFile = async function(filename) {
  let filepath = path.join(DOWNLOAD_PATH, filename);
  if (fs.existsSync(filepath)) {
    fs.unlinkSync(filepath);
  } else {
    Message({
      type: "info",
      message: "文件不存在"
    });
  }
};

export { getFileMD5, getChunkMD5, getChunk, getChunkNum, deleteFile };
